package demo.java.springboot.jpa.controller;

import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.SessionAttributes;

import demo.java.springboot.jpa.po.User;
import demo.java.springboot.jpa.service.UserService;

@Controller
@SessionAttributes("myUser")
public class UserController {
	private static Logger LOG = LogManager.getLogger(UserController.class);
	
	/**
	 * 加载主页面
	 * @param map
	 * @return
	 */
	@GetMapping("/")
	String toHome (Map<String, Object>map) {
		// 如果session中有用户，则进入主页，否则重定向进入登录页
		if (map.get("myUser") == null) {
			return "redirect:/login";
		}
		return "main";
	}
	
	/**
	 * 加载登录页面
	 * @return
	 */
	@GetMapping ("/login")
	String login () {
		return "login";
	}
	
	@Resource
	private UserService userService;
	
	/**
	 * 登录页面提交
	 * @param username
	 * @param password
	 * @param map
	 * @return
	 */
	@PostMapping ("/login")
	String login (String username, String password, Map<String, Object>map) {
		// 如果验证通过，则重定向到根路径，否则，返回登录页
		User u = userService.authenticate(username, password);
		if (u == null) {
			return "login";
		}
		map.put("myUser", u);
		return "redirect:/";
	}
}
